package com.huike.report.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.huike.clues.domain.vo.BusinessChangeStatisticsVo;
import com.huike.report.domain.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huike.business.mapper.TbBusinessMapper;
import com.huike.clues.domain.TbActivity;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.vo.IndexStatisticsVo;
import com.huike.clues.mapper.SysDeptMapper;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.clues.mapper.TbActivityMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.clues.mapper.TbClueMapper;
import com.huike.common.core.domain.entity.SysDept;
import com.huike.common.utils.SecurityUtils;
import com.huike.contract.domain.TbContract;
import com.huike.contract.mapper.TbContractMapper;
import com.huike.report.mapper.ReportMapper;
import com.huike.report.service.IReportService;

/**
 * 报告服务impl
 *
 * @author zhouao
 * @date 2022/05/16
 */
@Service
public class ReportServiceImpl implements IReportService {

    /**
     * 合同映射器
     */
    @Autowired
    private TbContractMapper contractMapper;


    /**
     * sys dict数据映射器
     */
    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    /**
     * 线索映射器
     */
    @Autowired
    private TbClueMapper clueMapper;

    /**
     * 活动映射器
     */
    @Autowired
    private TbActivityMapper activityMapper;

    /**
     * 业务映射器
     */
    @Autowired
    private TbBusinessMapper businessMapper;

    /**
     * 部门映射器
     */
    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 分配记录映射器
     */
    @Autowired
    private TbAssignRecordMapper assignRecordMapper;

    /**
     * 报告国会议员
     */
    @Autowired
    private ReportMapper reportMpper;

    /**
     * 合同统计
     *
     * @param beginCreateTime 开始创建时间
     * @param endCreateTime   最终创建时间
     * @return {@link LineChartVO}
     */
    @Override
    public LineChartVO contractStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVO lineChartVo = new LineChartVO();
        try {
            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            lineChartVo.setxAxis(timeList);
            List<LineSeriesVO> series = new ArrayList<>();
            List<Map<String, Object>> statistics = contractMapper.contractStatistics(beginCreateTime, endCreateTime);
            LineSeriesVO lineSeriesDTO1 = new LineSeriesVO();
            lineSeriesDTO1.setName("新增客户数");
            LineSeriesVO lineSeriesDTO2 = new LineSeriesVO();
            lineSeriesDTO2.setName("客户总数");
            int sum = 0;
            for (String s : timeList) {
                Optional optional = statistics.stream().filter(d -> d.get("dd").equals(s)).findFirst();
                if (optional.isPresent()) {
                    Map<String, Object> cuurentData = (Map<String, Object>) optional.get();
                    lineSeriesDTO1.getData().add(cuurentData.get("num"));
                    sum += Integer.parseInt(cuurentData.get("num").toString());
                } else {
                    lineSeriesDTO1.getData().add(0);
                }
                lineSeriesDTO2.getData().add(sum);
            }
            series.add(lineSeriesDTO1);
            series.add(lineSeriesDTO2);
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
            // e.printStackTrace();
        }
        return lineChartVo;
    }

    /**
     * 销售统计
     *
     * @param beginCreateTime 开始创建时间
     * @param endCreateTime   最终创建时间
     * @return {@link LineChartVO}
     */
    @Override
    public LineChartVO salesStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVO lineChartVo = new LineChartVO();
        try {
            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            lineChartVo.setxAxis(timeList);
            List<LineSeriesVO> series = new ArrayList<>();
            List<Map<String, Object>> statistics = contractMapper.salesStatistics(beginCreateTime, endCreateTime);
            LineSeriesVO lineSeriesVo = new LineSeriesVO();
            lineSeriesVo.setName("销售统计");
            int sum = 0;
            for (String s : timeList) {
                Optional optional = statistics.stream().filter(d -> d.get("dd").equals(s)).findFirst();
                if (optional.isPresent()) {
                    Map<String, Object> cuurentData = (Map<String, Object>) optional.get();
                    lineSeriesVo.getData().add(cuurentData.get("sales"));
                } else {
                    lineSeriesVo.getData().add(0);
                }
            }
            series.add(lineSeriesVo);
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
            // e.printStackTrace();
        }
        return lineChartVo;
    }


    /**
     * 香奈儿统计数据
     * 渠道统计
     *
     * @param beginCreateTime 开始创建时间
     * @param endCreateTime   最终创建时间
     * @return {@link List}<{@link Map}<{@link String}, {@link Object}>>
     */
    @Override
    public List<Map<String, Object>> chanelStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.chanelStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue = (String) datum.get("channel");
            String lable = sysDictDataMapper.selectDictLabel("clues_item", subjectValue);
            datum.put("channel", lable);
        }
        return data;
    }

    /**
     * 合同报告列表
     *
     * @param tbContract 结核病合同
     * @return {@link List}<{@link TbContract}>
     */
    @Override
    public List<TbContract> contractReportList(TbContract tbContract) {
        return contractMapper.selectTbContractList(tbContract);
    }


    /**
     * 活动统计
     *
     * @param beginCreateTime 开始创建时间
     * @param endCreateTime   最终创建时间
     * @return {@link List}<{@link Map}<{@link String}, {@link Object}>>
     */
    @Override
    public List<Map<String, Object>> activityStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.activityStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            Long activityId = (Long) datum.get("activity_id");
            TbActivity tbActivity = activityMapper.selectTbActivityById(activityId);
            if (tbActivity == null) {
                datum.put("activity", "其他");
            } else {
                datum.put("activity", tbActivity.getName());
            }
        }
        return data;
    }

    /**
     * 部门统计列表
     * 按照部门统计销售
     *
     * @param beginCreateTime 开始创建时间
     * @param endCreateTime   最终创建时间
     * @return {@link List}<{@link Map}<{@link String}, {@link Object}>>
     */
    @Override
    public List<Map<String, Object>> deptStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.deptStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            Long deptId = (Long) datum.get("dept_id");
            if (deptId != null) {
                SysDept dept = deptMapper.selectDeptById(deptId);
                datum.put("deptName", dept.getDeptName());
            }
        }
        return data;
    }


    /**
     * 频道统计列表
     * 按照渠道统计销售
     *
     * @param beginCreateTime 开始创建时间
     * @param endCreateTime   最终创建时间
     * @return {@link List}<{@link Map}<{@link String}, {@link Object}>>
     */
    @Override
    public List<Map<String, Object>> channelStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.channelStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue = (String) datum.get("channel");
            if (subjectValue != null) {
                String lable = sysDictDataMapper.selectDictLabel("clues_item", subjectValue);
                datum.put("channel", lable);
            }
        }
        return data;
    }


    /**
     * 主人船统计列表
     * 按照归属人统计销售
     *
     * @param beginCreateTime 开始创建时间
     * @param endCreateTime   最终创建时间
     * @return {@link List}<{@link Map}<{@link String}, {@link Object}>>
     */
    @Override
    public List<Map<String, Object>> ownerShipStatisticsList(String beginCreateTime, String endCreateTime) {
        return contractMapper.ownerShipStatistics(beginCreateTime, endCreateTime);
    }


    /**
     * 线索统计列表
     *
     * @param clue 线索
     * @return {@link List}<{@link TbClue}>
     */
    @Override
    public List<TbClue> cluesStatisticsList(TbClue clue) {
        return clueMapper.selectTbClueForReport(clue);
    }

    /**
     * 活动统计列表
     *
     * @param query 查询
     * @return {@link List}<{@link ActivityStatisticsVo}>
     */
    @Override
    public List<ActivityStatisticsVo> activityStatisticsList(TbActivity query) {
        query.setStatus("2");
        List<TbActivity> activities = activityMapper.selectTbActivityList(query);
        Map<String, Object> timeMap = query.getParams();
        List<ActivityStatisticsVo> list = new ArrayList<>();
        for (TbActivity activity : activities) {
            ActivityStatisticsVo dto = new ActivityStatisticsVo();
            BeanUtils.copyProperties(activity, dto);
            TbClue tbClue = new TbClue();
            tbClue.setActivityId(activity.getId());
            tbClue.setChannel(activity.getChannel());
            tbClue.setParams(timeMap);
            Map<String, Object> clueCount = clueMapper.countByActivity(tbClue);
            if (clueCount != null) {
                dto.setCluesNum(Integer.parseInt(clueCount.get("total").toString()));
                if (clueCount.get("falseClues") != null) {
                    dto.setFalseCluesNum(Integer.parseInt(clueCount.get("falseClues").toString()));
                }
                if (clueCount.get("toBusiness") != null) {
                    dto.setBusinessNum(Integer.parseInt(clueCount.get("toBusiness").toString()));
                }
            }
            TbContract tbContract = new TbContract();
            tbContract.setChannel(activity.getChannel());
            tbContract.setActivityId(activity.getId());
            tbContract.setParams(timeMap);
            Map<String, Object> contractCount = contractMapper.countByActivity(tbContract);
            if (contractCount != null) {
                dto.setCustomersNum(Integer.parseInt(contractCount.get("customersNum").toString()));
                if (contractCount.get("amount") == null) {
                    dto.setAmount(0d);
                } else {
                    dto.setAmount((Double) contractCount.get("amount"));
                }
                if (contractCount.get("cost") == null) {
                    dto.setCost(0d);
                } else {
                    dto.setCost((Double) contractCount.get("cost"));
                }

            }
            list.add(dto);
        }
        return list;
    }

    /**
     * 发现日期
     * *************看我看我**************
     * 传入两个时间范围，返回这两个时间范围内的所有时间，并保存在一个集合中
     *
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @return {@link List}<{@link String}>
     * @throws ParseException 解析异常
     */
    public static List<String> findDates(String beginTime, String endTime)
            throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dBegin = sdf.parse(beginTime);
        Date dEnd = sdf.parse(endTime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf.format(calBegin.getTime()));
        }
        System.out.println("时间==" + allDate);
        return allDate;
    }


    /**
     * 得到指数
     *
     * @param request 请求
     * @return {@link IndexVo}
     */
    @Override
    public IndexVo getIndex(IndexStatisticsVo request) {
        Long deptId = request.getDeptId();
        TbAssignRecord tbAssignRecord = new TbAssignRecord();
        tbAssignRecord.setLatest("1");
        assignRecordMapper.selectAssignRecordList(tbAssignRecord);
        return null;
    }

    /**
     * 销售统计指数
     *
     * @param request 请求
     * @return {@link List}<{@link Map}<{@link String}, {@link Object}>>
     */
    @Override
    public List<Map<String, Object>> salesStatisticsForIndex(IndexStatisticsVo request) {
        List<Map<String, Object>> list = contractMapper.contractStatisticsByUser(request);
        for (Map<String, Object> datum : list) {
            Long deptId = (Long) datum.get("dept_id");
            if (deptId != null) {
                SysDept dept = deptMapper.selectDeptById(deptId);
                datum.put("deptName", dept.getDeptName());
            }
        }
        return list;
    }


    /**
     * 把收音机
     * ************看我看我***********
     * 用我能少走很多路
     * 我是用来机选百分比的方法
     *
     * @param all 所有的
     * @param num 完成的
     * @return {@link BigDecimal}
     */
    private BigDecimal getRadio(Integer all, Long num) {
        if (all.intValue() == 0) {
            return new BigDecimal(0);
        }
        BigDecimal numBigDecimal = new BigDecimal(num);
        BigDecimal allBigDecimal = new BigDecimal(all);
        BigDecimal divide = numBigDecimal.divide(allBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
        return divide.multiply(new BigDecimal(100));
    }


    /**
     * 得到基本信息
     * 获取首页基本数据
     *
     * @param beginCreateTime 开始创建时间
     * @param endCreateTime   最终创建时间
     * @return {@link IndexBaseInfoVO}
     */
    @Override
    public IndexBaseInfoVO getBaseInfo(String beginCreateTime, String endCreateTime) {
        //1）构建一个空的结果集对象
        IndexBaseInfoVO result = new IndexBaseInfoVO();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();
        try {
            //3 封装结果集对象
            result.setCluesNum(reportMpper.getCluesNum(beginCreateTime, endCreateTime, username));
            result.setBusinessNum(reportMpper.getBusinessNum(beginCreateTime, endCreateTime, username));
            result.setContractNum(reportMpper.getContractNum(beginCreateTime, endCreateTime, username));
            result.setSalesAmount(reportMpper.getSalesAmount(beginCreateTime, endCreateTime, username));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //4 返回结果集对象
        return result;
    }

    @Override
    public IndexTodayInfoVO getTodayInfo(String time) {

        //1）构建一个空的结果集对象
        IndexTodayInfoVO result = new IndexTodayInfoVO();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();
        try {
            //3 封装结果集对象
            result.setTodayCluesNum(reportMpper.getCluesNum(time, time, username));
            result.setTodayBusinessNum(reportMpper.getBusinessNum(time, time, username));
            result.setTodayContractNum(reportMpper.getContractNum(time, time, username));
            result.setTodaySalesAmount(reportMpper.getSalesAmount(time, time, username));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

//        communicationTime
        return result;
    }

    /**
     * @param beginCreateTime:
     * @param endCreateTime:
     * @return IndexTodayInfoVO
     * @author Administrator
     * @description TODO
     * @date 2022/5/16 16:48
     */
    @Override
    public IndexTodoInfoVO getTodoInfo(String beginCreateTime, String endCreateTime) {

        //1）构建一个空的结果集对象
        IndexTodoInfoVO result = new IndexTodoInfoVO();
        //2 封装结果集属性
        try {
            result = reportMpper.getTodoInfo(beginCreateTime, endCreateTime);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return result;
    }

    /**
     * 统计图
     *
     * @param beginCreateTime:
     * @param endCreateTime:
     * @return Map<String, Integer>
     * @author Administrator
     * @description TODO
     * @date 2022/5/17 12:10
     */
    @Override
    public List<Map<String, Object>> subjectStatistics(String beginCreateTime, String endCreateTime) {
        return reportMpper.getsubJect(beginCreateTime, endCreateTime);
    }

    /**
     * 线索线性表
     *
     * @param beginCreateTime:
     * @param endCreateTime:
     * @return LineChartVO
     * @author Administrator
     * @description TODO
     * @date 2022/5/17 15:13
     */
    @Override
    public LineChartVO cluesStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVO lineChartVo = new LineChartVO();
        try {
            //遍历其中的时间
            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            //将时间信息存储在vo中 x轴
            lineChartVo.setxAxis(timeList);
            //创建一个信息对象 Y轴
            List<LineSeriesVO> series = new ArrayList<>();
            //执行sql语句 查找出这两段时间之间的信息
            List<Map<String, Object>> statistics = contractMapper.cluesStatistics(beginCreateTime, endCreateTime);
            //创建一个新的Y轴
            LineSeriesVO lineSeriesDTO1 = new LineSeriesVO();
            //复制 这个Y轴未 新增线信息
            lineSeriesDTO1.setName("新增线索数量");
            //创建第二个Y轴 这个Y轴为 线索总数量
            LineSeriesVO lineSeriesDTO2 = new LineSeriesVO();
            lineSeriesDTO2.setName("线索总数量");
            //若没有新增的则为0
            int sum = 0;
            //遍历时间集合 时间有多少，数据有多少
            for (String s : timeList) {
                //Optional<T>是一个可以包含或不可以包含非空值的容器对象
                Optional<Map<String, Object>> optional = statistics.stream().filter(
                        //将sql查询出的数据进行过滤
                        d -> d.get("dd").equals(s)).findFirst();
                //如果值不为空
                if (optional.isPresent()) {
                    //则将其中的数据取出来赋给 currenData对象
                    Map<String, Object> cuurentData = (Map<String, Object>) optional.get();
                    //获取线索数
                    lineSeriesDTO1.getData().add(cuurentData.get("num"));
                    //总线索数累加
                    sum += Integer.parseInt(cuurentData.get("num").toString());
                } else {
                    //否者今日就没有新增线索 第一个Y轴赋值为0
                    lineSeriesDTO1.getData().add(0);
                }
                //将总线索数赋值给第二个Y轴
                lineSeriesDTO2.getData().add(sum);
            }
            //将这两个Y轴封装到一个大的Y轴中
            series.add(lineSeriesDTO1);
            series.add(lineSeriesDTO2);
            //再将其中的数据封装到线性表 VO中
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
            // e.printStackTrace();
        }
        return lineChartVo;
    }

    /**
     * 漏斗图
     *
     * @param beginCreateTime:
     * @param endCreateTime:
     * @return VulnerabilityMapVo
     * @author Administrator
     * @description TODO
     * @date 2022/5/17 16:55
     */
    @Override
    public VulnerabilityMapVo getVulnerabilityMap(String beginCreateTime, String endCreateTime) {

        return reportMpper.getVulnerabilityMap(beginCreateTime, endCreateTime);
    }

    /**
     * 龙虎榜
     *
     * @param beginCreateTime:
     * @param endCreateTime:
     * @return List<HashMap < String, Object>>
     * @author Administrator
     * @description TODO
     * @date 2022/5/17 19:31
     */
    @Override
    public List<BusinessChangeStatisticsVo> businessChangeStatistics(String beginCreateTime, String endCreateTime) {
        //查询出所有商机与转换的合同数
        List<BusinessChangeStatisticsVo> list = reportMpper.businessChangeStatistics(beginCreateTime, endCreateTime);
        for (BusinessChangeStatisticsVo b : list) {
            Integer total = reportMpper.getTotal(beginCreateTime, endCreateTime);
            Integer num = b.getNum();
            BigDecimal radio = getRadio(total, Long.parseLong(String.valueOf(num)));
            b.setRadio(radio);
        }
        return list;
    }

    /**
     * 线索转化龙虎榜列表
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> clueChangeStatisticsForIndex(String beginCreateTime, String endCreateTime) {
        //3.获取所有的线索
        Integer countAllClues = clueMapper.countAllClues(beginCreateTime, endCreateTime);

        //1.获取线索转化列表
        List<Map<String, Object>> clueListByUserList = clueMapper.countAllClueListByUser(beginCreateTime, endCreateTime);
        for (Map<String, Object> map : clueListByUserList) {
            //获取转化量
            Long num = (Long) map.get("num");
            //2.此时map中包含了create_by,deptName,num等，但是没有包含radio转化率，所以此时要封装转化率
            map.put("radio",getRadio(countAllClues,num));
        }

        return clueListByUserList;
    }
}